package uk.ac.tees.aetoolkit;

import java.util.ArrayList;
import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Alarm class - used for creating, removing & updating alarms. An alarm can be
 * set using voice control or manual user input. Alarms have various settings
 * available such as questions to answer to see if the user truly is awake!
 * 
 * @author Sohail Rahman, Mark Williamson, Robert Sheffield
 */
public class Alarm extends Activity {

	/**
	 * Context variable set to this 'alarm'.
	 */
	private Context context = this;
	/**
	 * String variable used to store spoken words from the user.
	 */
	private String speech = "";

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_alarm);
		
		// Method used to set the ListView in the layout_alarm.
		setListView();
		// Method used to handle the actions of the buttons.
		handleButtons();
		// Sets an on click listener for the speech button.
				ImageButton alarmHelp = (ImageButton) findViewById(R.id.imageButton1);
				alarmHelp.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						AlertDialog alertDialog;
						AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
								Alarm.this);
						alertDialog2.setTitle("Help");
						alertDialog2
								.setMessage("Touchscreen use\n\nTo create a new alarm enter the time, enter an alarm description and select the days you want the alarm to be activated. You can then select to either wake up to the latest weather where you are, or a maths question to check you are fully awake!\n\nVoice Recognition use\n\nTo use the voice recognition, press the voice button, and when the chime sounds, say the time you would like to be woken up, and the alarm will be set. To set a time using a voice, you have to say the time in the following format, 15.15 would be said as quarter past three, 15.45 would be said as quarter to 4." +
										" this will set the time you requested automatically for you. ");
						alertDialog2.show();

					}
				});
	}

	/**
	 * This method is used to create and set the ListView appropriately.
	 */
	public void setListView() {
		// Creating an ArrayList for alarms.
		final ArrayList<String> alarms = new ArrayList<String>();
		// Retrieve SharedPreferences and Editor.
		SharedPreferences prefs = getSharedPreferences("pmd.aetoolkit", 0);
		final SharedPreferences.Editor editor = prefs.edit();
		// Adding 5 blank alarms to the ArrayList of alarms.
		for (int number = 0; number <= 4; number++) {
			alarms.add(prefs.getString("alarm" + number, ""));
		}
		// Defining the ListView from the layout.
		ListView listView = (ListView) findViewById(R.id.listview);
		// Creating ArrayAdapter using the list layout and alarms ArrayList.
		final ArrayAdapter<String> titleAdaptor = new ArrayAdapter<String>(
				getApplicationContext(), android.R.layout.simple_list_item_1,
				alarms);
		// Setting the ListViews ArrayAdapter.
		listView.setAdapter(titleAdaptor);
		// sets on item long click to listen for user input.
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> a, View v,
					final int p, long id) {
				// creates a dialog to prompt/notify the user.
				AlertDialog.Builder dialog = new AlertDialog.Builder(Alarm.this);
				dialog.setTitle("Delete");
				dialog.setMessage("Do you want to delete this alarm?");
				dialog.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface d, int w) {
								// Remove item from
								// ListView/ArrayList/ArrayAdapter.
								editor.remove("alarm" + p).commit();
								editor.putString("alarm" + p, "").commit();
								alarms.set(p, "");
								titleAdaptor.remove(titleAdaptor.getItem(p));
								titleAdaptor.notifyDataSetChanged();
								Intent i = new Intent(context, Alarm.class);
								startActivity(i);
							}
						});
				dialog.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface d, int w) {
							}
						});
				dialog.show();
				return true;
			}
		});
	}

	/**
	 * This method is used to handle the actions that occur when the buttons
	 * that are available on this layout are clicked.
	 */
	public void handleButtons() {
		// Set an onClickListener for add alarm button
		Button buttonAdd = (Button) findViewById(R.id.button1);
		buttonAdd.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(context, AddAlarm.class);
				startActivity(i);
			}
		});
		// Sets an on click listener for the speech button.
		ImageButton speak = (ImageButton) findViewById(R.id.btnSpeak);
		speak.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
				i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-UK");
				// Start speech synthesis if phone supports it.
				try {
					startActivityForResult(i, 1);
					speech = "";
				} catch (ActivityNotFoundException a) {
					Toast.makeText(getApplicationContext(),
							"Device doesnt support speech to text",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	/**
	 * Called when speech synthesis is started, used to determine what the user
	 * has said and add a relevant alarm accordingly.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		int minute = 0, hour = 0;
		// Flag to check if hour and minute has been set.
		boolean flag = false;
		if (resultCode == RESULT_OK && null != data) {
			// Creating an ArrayList to store speech data.
			ArrayList<String> text = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			// Setting speech variable to what the user has spoken.
			speech = text.get(0);
			// For loop to check the possible hour contained within the users
			// speech.
			for (int x = 0; x <= 12; x++) {
				// Checks if speech contains the hour and if so the minutes.
				if (speech.contains("" + x)) {
					if ((speech.contains("quarter past"))
							|| (speech.contains("quater past"))
							|| (speech.contains("water past"))) {
						hour = x;
						minute = 15;
						flag = true;
					} else if ((speech.contains("half past"))
							|| (speech.contains("arf past"))) {
						hour = x;
						minute = 30;
						flag = true;
					} else if ((speech.contains("quarter to"))
							|| (speech.contains("quater to"))
							|| (speech.contains("water to"))
							|| (speech.contains("water 2"))
							|| (speech.contains("quater 2"))
							|| (speech.contains("quarter 2"))) {
						hour = x - 1;
						minute = 45;
						flag = true;
					} else if ((speech.contains("o clock"))
							|| (speech.contains("o'clock"))) {
						hour = x;
						minute = 00;
						flag = true;
					}
					// If flag is false no statements where accepted.
					if ((flag == false) && (x == 12)) {
						Toast.makeText(context,
								"Speak in the format of 'Half past 5",
								Toast.LENGTH_SHORT).show();
					}
					// Check speech contains afternoon else default to AM.
					if (flag == true) {
						if ((speech.contains("afternoon"))
								|| (speech.contains("after noon"))) {
							hour = hour + 12;
							if (hour == 24 && minute != 45){
								hour = 00;
							}
						}
					}
				}
			}
		}
		// If the flag is true then add the alarm the user has spoken.
		if (flag == true) {
			// Get an instance of calendar for the current time.
			Calendar calNow = Calendar.getInstance();
			Calendar cal;
			cal = (Calendar) calNow.clone();
			// Set hour & minute of the calendar to what the user specified.
			cal.set(Calendar.HOUR_OF_DAY, hour);
			cal.set(Calendar.MINUTE, minute);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MILLISECOND, 0);
			// If the time has already been add 24 hours.
			if (cal.before(Calendar.getInstance())) {
				cal.add(Calendar.HOUR_OF_DAY, 24);
			}
			// Stores the text to display for this alarm.
			String display = hour + " : " + minute + " -" + "- Voice Alarm			";
			// Create an alarm manager.
			AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
			// Load SharedPreferences to pass through to the method.
			SharedPreferences prefs = getSharedPreferences("pmd.aetoolkit", 0);
			// Creates AddAlarm object & call appropriate method to add alarm.
			try{
			AddAlarm alarm = new AddAlarm();
			alarm.AddAnAlarm(prefs, alarmManager, context, display, "", cal);
			}catch (Exception e){
				Toast.makeText(this, "Limit reached! Delete/Edit an exsisting alarm!", Toast.LENGTH_SHORT).show();
			}
			// Method used to set the ListView in the layout_alarm.
			setListView();
			// Method used to handle the actions of the buttons.
			handleButtons();
		}
	}
}
